const express = require('express')
const qrcode = require('qrcode-terminal')

const reader = require('../utils/reader')
const { success, info } = require('../utils/output')
const getValidIPAddress = require('../utils/networkAddress')
const { staticPagePath, staticWarrantPath } = require('../utils/path')

module.exports = async () => {
  const app = express()

  // 读取本地文件 申请页面和凭证页面
  const [pageNotExists, page] = await reader(staticPagePath, false)
  const [warrantNotExists, warrant] = await reader(staticWarrantPath, false)

  // 获取本机 IPv4 地址和可用的端口
  const { IPAddress, port } = await getValidIPAddress()

  info('启动服务器...')

  app
    .use('/static', express.static('static'))
    .get('/', (_, res) => {
      pageNotExists ?
        res.status(500).send('Server Internal Error: Can Not Read File, Path: ' + staticPagePath) :
        res.status(200).setHeader('Content-Type', 'text/html').send(page)
    })
    .get('/warrant', (_, res) => {
      warrantNotExists ?
        res.status(500).send('Server Internal Error: Can Not Read File, Path: ' + staticWarrantPath) :
        res.status(200).setHeader('Content-Type', 'text/html').send(warrant)
    })
    .listen(port, () => {
      // 监听端口 生成二维码
      success('服务已启动')
      info(`本机地址  : http://localhost:${port}`)
      info(`局域网地址: http://${IPAddress}`)
      info('你可以扫描下面的二维码用同一局域网下的设备访问：')
      qrcode.generate(IPAddress)
    })
}